package com.easylinkin.linkappapi.circuit.job;

import com.easylinkin.linkappapi.circuit.entity.RailGiveSystemAlarm;
import com.easylinkin.linkappapi.circuit.mapper.RailGiveSystemAlarmMapper;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.device.service.DeviceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 告警信息定时任务
 * @author lyk
 * @date 2025/6/24 下午 1:54
 */
@Component
@EnableScheduling
public class GiveSystemAlarmJob {

    @Autowired
    private RailGiveSystemAlarmMapper alarmMapper;

    @Resource
    private DeviceService deviceService;

    @Resource
    private DeviceMapper deviceMapper;
    /**
     * 每天凌晨2点标记上一天AI告警记录已完成的逻辑
     */
    @Scheduled(cron = "0 0 2 * * ?")
    private void puruningResetAiSystemAlarm(){
        List<RailGiveSystemAlarm> alarms = alarmMapper.selectByOldDays();
        List<String> ids = new ArrayList<>();
        for(RailGiveSystemAlarm alarm:alarms){
            alarm.setModifyTime(new Date());
            alarm.setStatus(1);
            alarmMapper.updateById(alarm);
            if (!StringUtils.isEmpty(alarm.getDeviceCode())){
                Device oneByDeviceCode = deviceService.findOneByDeviceCode(alarm.getDeviceCode());
                if (Objects.nonNull(oneByDeviceCode)){
                    if (!ids.contains(oneByDeviceCode.getId())){
                        ids.add(oneByDeviceCode.getId());
                    }
                }
            }
        }
        if (ids.size()>0){
            for (String id:ids){
                deviceMapper.updateStatusById(id,0);
            }
        }

    }
}
